package top.xzxsrq.web.download;

import com.alibaba.fastjson.JSONObject;
import org.htmlunit.html.FrameWindow;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import top.xzxsrq.web.download.entity.PageInfo;
import top.xzxsrq.web.download.utils.HtmlUnits;

import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;

@Log4j2
public class CommonD {
    /**
     * 这个是本地检验的文件，同时也是存放获取的视频地址和视频时长
     */
    public static final String checkJsonFile = "__checkJsonFile.json";
    public static HtmlUnits htmlUnits = null;
    public String downloadTaskId;

    public String getDownloadType() {
        return "通用下载";
    }

    public boolean isDownloadPage(String pathUrl) {
        return true;
    }

    public static synchronized void close() {
        if (htmlUnits != null) {
            htmlUnits.close();
            htmlUnits = null;
        }
    }

    /**
     * 获取页面信息
     *
     * @param pageUrl        页面的url
     * @param downloadThread 下载线程
     * @param resourcesType  资源类型 new String[]{".mp4", ".m3u8"})
     * @param mediaEl        是否解析媒体元素
     * @return
     */
    public synchronized PageInfo getPageInfo(String pageUrl, DownloadThread downloadThread, String[] resourcesType, boolean mediaEl) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setDownloadType(getDownloadType());
        if (downloadThread.isCanStop()) {
            return pageInfo;
        }
        if (htmlUnits == null) {
            htmlUnits = new HtmlUnits();
        }
        log.info("开始打开页面 = " + pageUrl);
        try {
            htmlUnits.showUrl(pageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("打开页面错误：" + pageUrl);
            return pageInfo;
        }
        AtomicReference<String> src = new AtomicReference<>("");
        int waitTime = 30;
        while (waitTime != 0 && StringUtils.isEmpty(src.get())) {
            // https://yun.ssdm.cc/SBDM/SteinsGate01.m3u8
            List<String> resources = htmlUnits.getResources(resourcesType);
            log.info("资源路径打印===开始=========================================");
            resources.forEach(log::info);
            log.info("资源路径打印===结束=========================================");
            if (resources.size() >= 2) { // TODO 获取视频url
                src.set(resources.get(1));
            }
            if (mediaEl) {
                List<String> videoAndAudioUrl = htmlUnits.getVideoAndAudioUrl();
                log.info("videoAndAudioUrl打印===开始=========================================");
                videoAndAudioUrl.forEach(log::info);
                log.info("videoAndAudioUrl打印===结束=========================================");
                if (videoAndAudioUrl.size() >= 1) { // TODO 获取视频url
                    src.set(videoAndAudioUrl.get(0));
                }
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            waitTime--;
        }
        pageInfo.setDownloadUrl(src.get());
        pageInfo.setDownloadName(getPageDownLoadName(htmlUnits.getIframes()));
        return pageInfo;

    }

    public String getPageDownLoadName(List<FrameWindow> iframes) {
        return htmlUnits.getPage().getTitleText();
    }

    /**
     * 添加下载
     */
    public void addDownload(
            String downloadPage,
            String savePath
    ) {
        DownloadThread downloadThread = new DownloadThread();
        PageInfo pageInfo = getPageInfo(downloadPage, downloadThread, new String[]{".mp4", ".m3u8"}, true);
        downloadThread.setPageInfo(pageInfo);
        downloadThread.setSavePath(savePath);
        Future<Void> submit = DownloadManager.submit(downloadThread);
    }


    /**
     * 给web服务调用
     */
    public void webRunFunc(String downloadTaskId, String userBasePath, JSONObject jsonObject) throws Exception {

    }

    /**
     * 给web服务调用获取参数
     */
    public List<Map<Object, Object>> webRunFuncParams() {
        return new LinkedList<>();
    }

    /**
     * 给web服务调用获取参数，参数一定是双数<br/>
     * "prop",<br/>
     * videoUrl,<br/>
     * "label",<br/>
     * "视频直链",<br/>
     * "type",<br/>
     * "input"<br/>
     * 转成<br/>
     * Map<String, String> item = new HashMap<>();<br/>
     * item.put("prop", videoUrl);<br/>
     * item.put("label", "视频直链");<br/>
     * item.put("type", "input");
     */
    public Map<Object, Object> webRunFuncParam(Object... args) {
        Map<Object, Object> item = new HashMap<>();
        boolean b = args.length % 2 == 0;
        if (!b) {
            return item;
        }
        for (int i = 0; i < args.length; i += 2) {
            item.put(args[i], args[i + 1]);
        }
        return item;
    }

    /**
     * 数组用
     *
     * @param args
     * @return
     */
    @SafeVarargs
    public final List<Map<Object, Object>> webRunFuncParamList(Map<Object, Object>... args) {
        return new LinkedList<>(Arrays.asList(args));
    }

    /**
     * url解析成参数，返回null表示没有实现，返回一个new JSONObject();表示没有url传入进行解析
     *
     * @param jsonObject
     * @return
     */
    public JSONObject urlParse(JSONObject jsonObject) {
        return null;
    }
}
